package com.co.controller;

import java.util.ArrayList;

import org.hibernate.Session;

import com.co.model.bean.User;
import com.co.persistence.HibernateUtils;
import com.co.persistence.PersistenceManager;
import com.co.utils.Constants;
import com.co.utils.JPage;
import com.co.utils.Logger;

public class LoginPageController {

	private static LoginPageController loginPageControllerInstance;
	private GlobalConfigurationManager gcmInstance;
	private ViewManager viewManager;
	private JPage page;

	public LoginPageController() {
		gcmInstance = GlobalConfigurationManager.getInstance();
		viewManager = ViewManager.getInstance();
	}

	public static LoginPageController getInstance() {
		if (loginPageControllerInstance == null) {
			loginPageControllerInstance = new LoginPageController();
		}
		return loginPageControllerInstance;
	}

	public boolean validateLogin(String name, String password) {
		Session session = null;
		boolean correctLogin = false;
		ArrayList<User> users = null;
		try {

			PersistenceManager manager = PersistenceManager.getInstance();

			HibernateUtils u = new HibernateUtils();
			session = u.getSessionFactory().openSession();

			// Using from Clause
			// String strQuery = "from User u";
			// String strQuery = "from User u";
			// List<User> listUsers = selectRows(session, strQuery);
			//
			// String strQuery = "from User u";
			String strQuery = "from User u where u.name = '" + name
					+ "' and u.password = '" + password + "'";
			users = manager.selectUsers(session, strQuery);

		} catch (Exception e) {

		} finally {

		}
		if (!users.isEmpty())
			correctLogin = true;

		return correctLogin;
	}

	private void setPage(JPage page) {
		this.page = page;
	}

	private JPage getPage() {
		return this.page;
	}

	public void configure(String pageId, JPage page) {
		setPage(page);
		gcmInstance.configurePage(page);
		viewManager.suscriptPage(pageId, page);
	}

	public void login(String user, String password) {
		if (validateLogin(user, password)) {
			Logger.showMessage("- loginValid -");
			viewManager.goToPage(Constants.MAIN_MENU_PAGE);

		} else
			Logger.showMessage("- loginNotValid -");

	}

}
